package com.wwj.core.app.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wwj.core.app.entity.Version;
import com.wwj.core.app.entity.mapper.VersionMapper;
import com.wwj.core.app.service.IVersionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

/**
 * Created by xya on 16-10-24.
 */
@Service
public class VersionServiceImpl implements IVersionService {

    @Resource
    private VersionMapper versionMapper;

    @Override
    public Page<Version> findByPage(int offset, int limit, Map<String, Object> params) {
        PageHelper.offsetPage(offset, limit);
        return (Page<Version>) versionMapper.selectVersions(params);
    }

    @Override
    public void addVersion(Version version) {
        version.setPublishTime(new Date());
        if(version.getStatus() == 0) {
            version.setStopTime(new Date());
        }
        versionMapper.insertVersion(version);
    }

    @Override
    public void modifyVersion(Version version) {
        Version old = versionMapper.selectVersionById(version.getId());
        if(old.getStatus() == 1 && version.getStatus() == 0) {
            version.setStopTime(new Date());
        } else {
            version.setStopTime(old.getStopTime());
        }
        versionMapper.updateVersion(version);
    }

    @Override
    public Version findById(Integer id) {
        return versionMapper.selectVersionById(id);
    }

    @Override
    public Version dealValidateVersionNo(String versionNo, String os) {
        Version version = versionMapper.selectVersionByNo(versionNo, os);
        if(version == null) {
            synchronized (this) {
                version = versionMapper.selectVersionByNo(versionNo, os);
                if(version == null) {
                    version = new Version();
                    version.setVersionNo(versionNo);
                    version.setOs(os);
                    if("ios".equalsIgnoreCase(os)) {
                        version.setVersionName("IOS版本" + versionNo);
                    } else if("android".equalsIgnoreCase(os)) {
                        version.setVersionName("Android版本" + versionNo);
                    } else {
                        version.setVersionName("其他手机系统版本" + versionNo);
                    }
                    version.setPublishTime(new Date());
                    version.setStatus(1);
                    versionMapper.insertVersion(version);
                }
            }
        }
        return version;
    }

}
